package com.yiwei.jmx.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.yiwei.jmx.R;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.ZhiMaCertBean;
import com.yiwei.jmx.api.bean.ZhiMaCertQueryBean;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.Const;
import com.yiwei.jmx.event.OnZhiMaEventMsg;
import com.yiwei.jmx.util.Dialog;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.PreferenceUtils;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.net.URLEncoder;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * Created by Administrator on 2018/6/10.
 */

public class FaceIdentityZhiMaActivity extends BaseActivity {

    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.btn_wechat)
    ImageView btnWechat;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.img_icon_gif)
    GifImageView imgIconGif;
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.txt_agree)
    TextView txtAgree;
    private Unbinder unbinder;
    private boolean isFromLoan;
    private GifDrawable gifDrawable;
    private String verityUrl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_identity_zhima);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("人脸认证");
        isFromLoan = getIntent().getBooleanExtra("isFromLoan", true);

        EventBus.getDefault().register(this);
        PreferenceUtils.remove(this, "isfromAlipay");
        PreferenceUtils.remove(this, "zhima_biz_no");
//        Glide.with(this).load(R.mipmap.img_face_gif).asGif().into(imgIconGif);
//        imgIconGif.setVisibility(View.VISIBLE);
        if (isEnoughMem()) {
            imgIconGif.setImageResource(R.mipmap.img_face_gif);
            gifDrawable = (GifDrawable) imgIconGif.getDrawable();
        }
        getZhiMaCertInfo(true);
    }

    private boolean isEnoughMem() {
        File path = Environment.getDataDirectory();  // Get the path /data, this is internal storage path.
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        long memSize = availableBlocks * blockSize;  // free size, unit is byte.

        if (memSize < 1024 * 1024 * 10) { //If phone available memory is less than 10M , kill activity,it will avoid force when phone low memory.
            return false;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(PreferenceUtils.getString(this, "zhima_biz_no", ""))) {
            if (!PreferenceUtils.getBoolean(this, "isfromAlipay", false)) {
                getCertqueryInfo();
            }
        }
        if (isEnoughMem() && gifDrawable != null) {
            gifDrawable.start();
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (gifDrawable != null) {
            gifDrawable.pause();
        }
    }

    /**
     * 获取url和biz_no
     */
    private void getZhiMaCertInfo(boolean isFirst) {


        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        ZhiMaCertBean bean = new ZhiMaCertBean();
        bean.schema = Const.ZHI_MA_SCHEMA;
        Api.api_service.getZhimaCert(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.data.isMust.equals("1")) {
                        verityUrl = result.data.url;
                        PreferenceUtils.putString(this, "zhima_biz_no", result.data.biz_no);
                        if (isFirst) {
                            return;
                        }
                        doVerify(result.data.url);
                        verityUrl="";
                    } else {
                        startTwo();
                    }
                });


    }


    /**
     * 启动支付宝进行认证
     *
     * @param url 开放平台返回的URL
     */
    private void doVerify(String url) {
        if (Util.isAppInstalled(this, "com.eg.android.AlipayGphone")) {
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
            builder.append(URLEncoder.encode(url));
            action.setData(Uri.parse(builder.toString()));
            startActivity(action);
//            isVerify = true;
        } else {
            //处理没有安装支付宝的情况
            Dialog.showDefaultDialog(this, "", getString(R.string.download_alipay_tishi), getString(R.string.forget_it), getString(R.string.good), false, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    Intent action = new Intent(Intent.ACTION_VIEW);
                    action.setData(Uri.parse("https://m.alipay.com"));
                    startActivity(action);
                }

                @Override
                public void cancel() {

                }
            });
        }
    }

    /**
     * 获取认证结果查询
     */
    private void getCertqueryInfo() {

        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        ZhiMaCertQueryBean bean = new ZhiMaCertQueryBean();
        bean.biz_no = PreferenceUtils.getString(this, "zhima_biz_no", "");
        Api.api_service.getZhiMaCertquery(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "人脸认证成功", Toast.LENGTH_SHORT).show();
                    PreferenceUtils.remove(FaceIdentityZhiMaActivity.this, "zhima_biz_no");
//                sendEvent();
                    startTwo();
                });
    }

    private void startTwo() {
        if (isFromLoan) {
            Intent intent = new Intent(this, FaceIdentityActivity.class);
            intent.putExtra("isFromLoan", true);
            startActivity(intent);
            finish();
        } else {
            finish();
        }

    }


    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OnZhiMaEventMsg(OnZhiMaEventMsg msg) {
        getCertqueryInfo();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
        unbinder = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_submit, R.id.txt_agree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_submit:
                if(TextUtils.isEmpty(verityUrl)){
                    getZhiMaCertInfo(false);
                }else {
                    doVerify(verityUrl);
                }
                break;
            case R.id.txt_agree:
                break;
        }
    }
}
